package com.sina.shop.manage.dao.foot;

import com.sina.shop.dao.ShopDataSourceDao;
import com.sina.shop.domain.Status;
import com.sina.shop.domain.foot.Foot;
import com.sina.shop.domain.foot.Foot_;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * description:
 * 段浩杰 2018-01-14 20:47
 */
@Repository("footManageDao")
public class FootManageDaoImpl extends ShopDataSourceDao implements FootManageDao {

    @Override
    public int deleteFoot(Long id) {
        String hql = "update Foot f set f.status=:status where f.id = :id";
        return template.executeWithNativeSession(session -> {
            Query query = session.createQuery(hql);
            query.setParameter("id", id);
            query.setParameter("status", Status.NOT_USE);
            return query.executeUpdate();
        });
    }

    @Override
    public Foot getFootByAidAndGid(Long adminId, Long goodsId) {
        String hql = "from Foot f where f.admin.id=:adminId and f.goods.id=:goodsId";
        return unique(hql, new String[]{"adminId", "goodsId"}, new Object[]{adminId, goodsId});
    }

    @Override
    public List<Map<String, Object>> getFootList(Foot foot) {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<Foot> root = criteriaQuery.from(Foot.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    footSelection(root)
            );

            Predicate predicate = footPredicate(foot, builder, root);
            //指定查询条件
            criteriaQuery.where(predicate);
            //指定用于排序查询结果的排序表达式
            criteriaQuery.orderBy(
                    builder.asc(root.get(Foot_.admin)),
                    builder.desc(root.get(Foot_.createTime)),
                    builder.asc(root.get(Foot_.id))
            );

            //创建查询
            Query<Tuple> query = session.createQuery(criteriaQuery);
            //得到起始条数
            int first = (foot.getPage() - 1) * foot.getRows();

            query.setFirstResult(first);
            query.setMaxResults(foot.getRows());
            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }

    @Override
    public Long getFootCount(Foot foot) {
        return template.executeWithNativeSession(session -> {

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
            Root<Foot> root = criteriaQuery.from(Foot.class);
            //根据id查找结果数
            criteriaQuery.select(
                    builder.count(root.get(Foot_.id))
            );
            //组装查询条件
            criteriaQuery.where(
                    footPredicate(foot, builder, root)
            );
            //创建插叙语句
            Query<Long> query = session.createQuery(criteriaQuery);
            long count;
            try {
                //得到结果条数
                count = query.getSingleResult();
            } catch (NoResultException e) {
                count = 0;
            }
            return count;
        });
    }

    /**
     * 查询条件组装类
     *
     * @param foot
     * @param builder
     * @param root
     * @return
     */
    protected Predicate footPredicate(Foot foot, CriteriaBuilder builder
            , Root<Foot> root) {
        List<Predicate> list = new ArrayList<>(4);

        if (foot.getLastId() != null) {
            list.add(
                    builder.lt(root.get(Foot_.id), foot.getLastId())
            );
        }

        if (foot.getAdmin() != null) {
            list.add(
                    builder.equal(root.get(Foot_.admin), foot.getAdmin().getId())
            );
        }

        if (foot.getCreateStart() != null) {
            list.add(
                    builder.greaterThanOrEqualTo(root.get(Foot_.createTime), foot.getCreateStart())
            );
        }

        if (foot.getCreateEnd() != null) {
            list.add(
                    builder.lessThanOrEqualTo(root.get(Foot_.createTime), foot.getCreateEnd())
            );
        }

        return builder.and(
                list.toArray(new Predicate[list.size()])
        );
    }

    /**
     * 所要查询的字段组装类
     *
     * @param root
     * @return
     */
    protected List<Selection<?>> footSelection(Root<Foot> root) {

        List<Selection<?>> list = new ArrayList<>(12);
        /**
         * 五条一组
         */
        list.add(root.get(Foot_.id).as(Long.class).alias("id"));//id
        list.add(root.get(Foot_.admin).alias("admin"));//
        list.add(root.get(Foot_.goods).alias("goods"));
        list.add(root.get(Foot_.createTime).alias("createTime"));
        list.add(root.get(Foot_.status).alias("status"));

        return list;
    }
}
